const inputOnly = {
  bind(el, vDir, vNode) {
    // vDir.value 有指令的参数
    let content;
    function keyPressFun(event) {
      let e = event || window.event;
      let inputKey = String.fromCharCode(
        typeof e.charCode === "number" ? e.charCode : e.keyCode
      );
      let re = /\d|\./;
      content = e.target.value;
      //定义方法,阻止输入
      function preventInput() {
        if (e.preventDefault) {
          e.preventDefault();
        } else {
          e.returnValue = false;
        }
      }
      if (
        (!re.test(inputKey) && !e.ctrlKey) ||
        (content.indexOf(".") > 0 && inputKey == ".")
      ) {
        preventInput();
      }
    }
    function keyUpFun(event) {
      let e = event || window.event;
      content = parseFloat(e.target.value);
      if (!content) {
        return;
        // content = 0.00;
      }
      let arg_max = "";
      let arg_length = "";
      if (vDir.value) {
        arg_max = parseFloat(vDir.value.max);
        arg_length = parseInt(vDir.value.length);
      }
      if (arg_max !== "" && content > arg_max) {
        e.target.value = arg_max;
        vNode.componentInstance.$emit("input", e.target.value);
        content = arg_max;
      }
      if (arg_length) {
        e.target.value = e.target.value.toString().substring(0, arg_length);
        vNode.componentInstance.$emit("input", e.target.value);
        content = e.target.value;
      }
    }
    function focusOutFun(event) {
      let e = event || window.event;
      let arg_min = "";
      if (vDir.value) arg_min = parseFloat(vDir.value.min);
      content =
        e.target.value !== null && e.target.value !== undefined
          ? e.target.value
              .toString()
              .replace(/([^\u0000-\u00FF])/g, "")
              .replace(/\s+/g, "")
          : null;
      if (!content) {
        vNode.componentInstance.$emit("input", null);
        return;
      }
      let currentDecimal = content.split(".")[1]
        ? content.split(".")[1].length
        : 0;
      if (arg_min !== "" && parseFloat(content) < arg_min) {
        content = arg_min;
      }
      let arg_precision = 0; //默认保留至整数
      if (vDir.value && vDir.value.precision !== undefined) {
        content = parseFloat(content);
        arg_precision = parseFloat(vDir.value.precision);
        e.target.value = content;
        if (currentDecimal > arg_precision) {
          e.target.value = content.toFixed(arg_precision);
        }
        vNode.componentInstance.$emit("input", e.target.value);
      }
    }
    //按键按下
    el.addEventListener("keypress", keyPressFun);
    //按键弹起=>并限制最大最小
    el.addEventListener("keyup", keyUpFun);
    //失去焦点=>保留指定位小数
    el.addEventListener("focusout", focusOutFun);
  }
};

const install = function(Vue) {
  Vue.directive("inputOnly", inputOnly);
};

if (window.Vue) {
  window["inputOnly"] = inputOnly;
  Vue.use(install); // eslint-disable-line
}

inputOnly.install = install;
export default inputOnly;
